var app = {
  didTranslate: false
};

match_list = [];
chrome.storage.local.get(null, function(items) {
	if (items['temp_translate']) { //切换语言后刷新页面直接翻译
		injectBar(items['temp_translate'][1], items['temp_translate'][2], langmap);
		translate(items['temp_translate'][1], items['temp_translate'][2]);
	} else if (items['custom_switch']) { //自动翻译流程
		for (i in items['custom_sites']) {
			match_list.push(".*" + items['custom_sites'][i] + '*')
		}

		if (match_list.length == 0) {
			if (!items['ban_detect'] && window.location.href.indexOf("newtab") < 0) {
				langDetect();
			}
			return;
		}

		var re = new RegExp(match_list.join("|"));

		if (re.test(window.location.href)) {
			injectBar('auto', 'zh', langmap);
			translate();
		} else {
			if (!items['ban_detect'] && window.location.href.indexOf("newtab") < 0) {
				langDetect();
			}
		}
	} else { //屏蔽空白页调用语言检测
		if (!items['ban_detect'] && window.location.href.indexOf("newtab") < 0) {
			langDetect();
		}
	}
	chrome.storage.local.set({
		'temp_translate': false,
	});
});

chrome.runtime.onMessage.addListener(function(data, sender, sendResponse) {
  if (data.action === 'getDidTranslate') {
    sendResponse({
      didTranslate: app.didTranslate
    });
  }
});
function translateByPopup() {
  setTimeout(function() {
    if ($('#translate-head').length <= 0) {
      injectBar('auto', 'zh', langmap);
      translate();
    } else if ($('#translate-head').is(':hidden')) {
        app.didTranslate = true;
      $('#translate-head').show();
      var body_margin_top = $('body').css('margin-top');
      var new_margin_top = parseInt(body_margin_top);
      new_margin_top += 36;
      $('body').attr('style', 'position: relative; margin-top: ' + new_margin_top + 'px !important;');
      $('trans').each(function() {
        $(this).text($(this).attr('data-dst'));
      });
      $('#src-reload').text('显示原文');
    }
  }, 0);
}
